package com.zzh.zzhaiagent.filter;

import cn.hutool.core.util.StrUtil;
import com.zzh.zzhaiagent.domain.vo.UserProfilesVO;
import com.zzh.zzhaiagent.exception.BusinessException;
import com.zzh.zzhaiagent.utils.*;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import static com.zzh.zzhaiagent.constant.RedisKeyConstant.USER_INFO_KEY_PREFIX;

/**
 * @author: zzh
 * @date: 2025/05/30 10:43:13
 * @version: 1.0
 */
//前面的TokenAuthenticationFilter认证完毕后，去校验token次数是否够用，
@Component
@Slf4j
@Order(3)
public class TokenAILoveAgentFilter implements HandlerInterceptor {

    @Resource
    private RedisHutoolHashUtil redisHutoolHashUtil;

    /**
     * 请求预处理
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        UserProfilesVO attribute = WebFrameworkUtils.getUserInfo(request);
        if (attribute == null){
            log.error("次数用完了");
            throw new BusinessException(ResultCodeEnum.TOKEN_COUNT_OUT_OF_LIMIT);
            //return false;
        }
        Long token = attribute.getToken();
        if (token == null || token == 0){
            log.error("次数用完了");
            throw new BusinessException(ResultCodeEnum.TOKEN_COUNT_OUT_OF_LIMIT);
            //return false;
        }
        return true;//放行
    }


    /**
     * 请求拦截器执行完回调方法
     * @param request
     * @param response
     * @param handler
     * @param ex
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
//        request.removeAttribute("user");

    }


}
